<template>
  <div id="Picture">
    <div class="picture_upload">
      <a-upload
        list-type="picture-card"
        :show-upload-list="false"
        :custom-request="handleUpload"
        :before-upload="beforeUpload"
      >
        <img v-if="picture?.url" :src="picture?.url" alt="avatar" />
        <div v-else>
          <loading-outlined v-if="loading"></loading-outlined>
          <plus-outlined v-else></plus-outlined>
          <div class="ant-upload-text">点击或拖拽上传图片</div>
        </div>
      </a-upload>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { uploadFileUsingPost } from '@/api/fileController'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons-vue'
import type { UploadProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import { ref } from 'vue'

//定义属性
interface Props {
  picture?: string
  onSuccess?: (newPicture: any) => void
}
const props = defineProps<Props>()
const loading = ref<boolean>(false)

//校验图片格式和内存
const beforeUpload = (file: UploadProps['fileList'][number]) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('不支持上传该格式的图片，推荐 JPG/PNG 格式!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('不能上传超过 2MB 的图片!')
  }
  return isJpgOrPng && isLt2M
}
/**
 * 上传图片
 * @param param
 */
const handleUpload = async ({ file }: any) => {
  loading.value = true
  try {
    const params = props.picture ? { id: props.picture.id } : {}
    const res = await uploadFileUsingPost(params, file)
    if (res.data.code === 0 && res.data.data) {
      console.log('图片', res)
      props.onSuccess?.(res.data.data)
    } else {
      message.error('图片上传失败，' + res.data.message)
    }
  } catch (error) {
    message.error('图片上传失败')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
#Picture {
  .picture_upload :deep(.ant-upload) {
    width: 100% !important;
    height: 100% !important;
    min-height: 152px;
    min-width: 152px;

    img {
      max-width: 100%;
      max-height: 400px;
    }

    .ant-upload-text {
      margin-top: 8px;
      font-size: 16px;
      color: #666;
    }

    &.ant-upload-select {
      .anticon {
        svg {
          font-size: 32px;
          color: #999;
        }
      }
    }
  }
}
</style>
